package com.jinzhi.jzweb.controller;


import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.mapper.Wrapper;
import com.jinzhi.common.utils.StringUtil;
import com.jinzhi.jzweb.dao.moduleConfig.JzJinzhuanDispositionModuleMapper;
import com.jinzhi.jzweb.domain.ExaminationBatchComSDO;
import com.jinzhi.jzweb.pojo.ModuleConfig.JzJinzhuanDispositionModule;
import com.jinzhi.jzweb.pojo.ModuleConfig.JzJinzhuanDispositionTopic;
import com.jinzhi.jzweb.service.ExaminationBatchComSService;
import com.jinzhi.jzweb.service.moduleConfig.IJzJinzhuanDispositionModuleService;
import com.jinzhi.jzweb.service.moduleConfig.IJzJinzhuanDispositionTopicService;
import com.jinzhi.sys.service.SysUserRelevancyService;
import com.jinzhi.sys.service.UserRoleService;
import com.jinzhi.sys.service.UserService;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.jinzhi.common.annotation.Log;
import com.jinzhi.common.base.BaseController;
import com.jinzhi.jzweb.domain.ExaminationBatchComDO;
import com.jinzhi.jzweb.service.ExaminationBatchComService;
import com.jinzhi.common.utils.Result;

/**
 *
 * <pre>
 * 竞赛考试批次管理
 * </pre>
 * <small> 2023-05-07 14:59:39 | lance</small>
 */
@Controller
@RequestMapping("/jzweb/examinationBatchCom")
public class ExaminationBatchComController extends BaseController {
    @Autowired
    private ExaminationBatchComService examinationBatchComService;
    @Autowired
    SysUserRelevancyService userRelevancyService;
    @Autowired
    UserService userService;
    @Autowired
    private UserRoleService userRoleService;
    @Autowired
    private ExaminationBatchComSService examinationBatchComServices;

    @Autowired
    private IJzJinzhuanDispositionModuleService dispositionModuleService;

    @Autowired
    private  IJzJinzhuanDispositionTopicService dispositionTopicService;

    @GetMapping()
    @RequiresPermissions("jzweb:examinationBatchCom:examinationBatchCom")
    String ExaminationBatchCom(Integer type,Model model){
        model.addAttribute("type",type);
        return "jzweb/examinationBatchCom/examinationBatchCom";
    }

    @ResponseBody
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    @RequiresPermissions("jzweb:examinationBatchCom:examinationBatchCom")
    public Result<Page<ExaminationBatchComDO>> list( ExaminationBatchComDO examinationBatchComDTO){
        EntityWrapper<ExaminationBatchComDO> wrapper = new EntityWrapper<>();
        Page<ExaminationBatchComDO> page =null;
        if(StringUtil.notEmpty(examinationBatchComDTO.getCompetitionType())){
            wrapper.addFilter("{0} like CONCAT('%',competition_type,'%')", examinationBatchComDTO.getCompetitionType());
        }
        // 查询列表数据
        if(examinationBatchComDTO.getType()==4){
            //1650432312954884097;;1654825643938709505;;1655451892407132162
            //1628314089924603905;;1638449851768819713;;1641246520054296578
            //用户信息
            List<String> organizationNewsDOS = userRoleService.selroleNameList(this.getUserId());
            //for(RoleDO li:listRole){
            if(StringUtils.isBlank(this.getUser().getTrack())){
                //身份为null或者""，超级管理员
                page = examinationBatchComService.selectPage(getPage(ExaminationBatchComDO.class),
                        wrapper.eq("type",examinationBatchComDTO.getType()).like("name",examinationBatchComDTO.getName()).orderBy("id", false));

            }
            if(!StringUtils.isBlank(this.getUser().getTrack())&&this.getUser().getTrack().equals("E")){
                //一级管理员
                //一级管理员查询创建的
                page = examinationBatchComService.selectPage(getPage(ExaminationBatchComDO.class),
                        wrapper.eq("create_id",this.getUserId()).eq("type",examinationBatchComDTO.getType())
                                .orderBy("id", false));
            }else if(!StringUtils.isBlank(this.getUser().getTrack()) && !this.getUser().getTrack().equals("E")){
                //工作人员,根据工作人员id查询绑定模版id，根据模版id查询绑定批次id，根据批次查询批次信息
                 List<JzJinzhuanDispositionTopic> dispos = dispositionTopicService.selectList(new EntityWrapper<JzJinzhuanDispositionTopic>().like("referee_id",this.getUserId().toString()));
                 if(dispos.isEmpty()){
                     return null;
                 }
                 List<Long> modileIds = dispos.stream().map(JzJinzhuanDispositionTopic::getModuleId).distinct().collect(Collectors.toList());
                 List<ExaminationBatchComSDO> sdos = examinationBatchComServices.selectList(new EntityWrapper<ExaminationBatchComSDO>().in("modile_id",modileIds));
                List<Long> sdoIds = sdos.stream().map(ExaminationBatchComSDO::getPId).distinct().collect(Collectors.toList());
                 wrapper.like("name",examinationBatchComDTO.getName())
                        .in("id",sdoIds)
                        .eq("type",examinationBatchComDTO.getType());

                page = examinationBatchComService.selectPage(getPage(ExaminationBatchComDO.class), wrapper);
            }
        }else {
            page = examinationBatchComService.selectPage(getPage(ExaminationBatchComDO.class),
                    wrapper.eq("type",examinationBatchComDTO.getType()).like("name",examinationBatchComDTO.getName()).orderBy("id", false));
        }
        List<ExaminationBatchComDO> list = new ArrayList();
        for (int i = 0; i < page.getRecords().size(); i++) {
            ExaminationBatchComDO obj = (ExaminationBatchComDO) page.getRecords().get(i);
            list.add(obj);
        }
        int p=list.size();
        for (int i = 0; i < p; i++) {

            List<ExaminationBatchComSDO>  lists= examinationBatchComServices.findByKv("pid",list.get(i).getId());
            for(ExaminationBatchComSDO  li:lists ){
                ExaminationBatchComDO sdo=new ExaminationBatchComDO();
                sdo.setName(li.getName());
                sdo.setCompetitionType(list.get(i).getCompetitionType());
                sdo.setPid(list.get(i).getId());
                sdo.setId(li.getId());
                sdo.setState(1);
                sdo.setCbatchId(list.get(i).getCbatchId());
                sdo.setModileId(li.getModileId());
                sdo.setType(li.getType());
                sdo.setStartTime(li.getStartTime());
                sdo.setEndTime(li.getEndTime());
                //拼接模版信息
                if(Objects.nonNull(li.getModileId())){
                    JzJinzhuanDispositionModule jinzhuanDispositionModule = new JzJinzhuanDispositionModule().setId(li.getModileId());
                    List<JzJinzhuanDispositionModule> modules = dispositionModuleService.getModuleList(jinzhuanDispositionModule);
                    if(!modules.isEmpty()){
                        jinzhuanDispositionModule = modules.get(0);
                    }
                    sdo.setDispositionModule(jinzhuanDispositionModule);
                }
                list.add(sdo);
            }
            //拼接模版信息
            if(Objects.nonNull(list.get(i).getModileId())){
                JzJinzhuanDispositionModule jinzhuanDispositionModule = new JzJinzhuanDispositionModule().setId(list.get(i).getModileId());
                List<JzJinzhuanDispositionModule> modules = dispositionModuleService.getModuleList(jinzhuanDispositionModule);
                if(!modules.isEmpty()){
                    jinzhuanDispositionModule = modules.get(0);
                }
                list.get(i).setDispositionModule(jinzhuanDispositionModule);
            }
        }


        page.setRecords(list);
        return Result.ok(page);
    }

    @Log("审核")
    @PostMapping("/review")
    @ResponseBody
    @RequiresPermissions("jzweb:examinationBatch:review")
    public Result<String> review(@RequestParam("ids[]") Long[] ids, Integer state, String remark) {
        if (state.equals(2) || state.equals(1)) {
            int i = 0;
            for (Long id : ids) {
                ExaminationBatchComDO examinationBatchDO = examinationBatchComService.selectById(id);
                if (examinationBatchDO != null) {
                    examinationBatchDO.setState(state);
                    examinationBatchDO.setCheckerId(this.getUserId());
                    examinationBatchDO.setCheckerDate(new Date());
                    if (state.equals(2)) {
                        examinationBatchDO.setRemark(remark);//未通过，添加备注
                    } else {
                        examinationBatchDO.setRemark("");//审核通过，清空备注
                    }
                    boolean b = examinationBatchComService.updateById(examinationBatchDO);
                    if (b) {
                        i++;
                    } else {
                        break;
                    }
                }
            }
            if (i == ids.length) {
                return Result.build(0, "已成功审核：" + i + "条数据");
            } else {
                return Result.fail("审核状态修改失败！");
            }
        } else {
            return Result.fail("审核状态修改失败！");
        }
    }


    @GetMapping("/add")
    @RequiresPermissions("jzweb:examinationBatchCom:add")
    String add(){
        return "jzweb/examinationBatchCom/add";
    }

    @GetMapping("/adds")
    @RequiresPermissions("jzweb:examinationBatchCom:add")
    String adds( Long id,Model model,Long cbatchId){
        model.addAttribute("id", id);
        model.addAttribute("cbatchId", cbatchId);
        return "jzweb/examinationBatchCom/adds";
    }


//    @GetMapping("/adds")
//    @RequiresPermissions("jzweb:examinationBatchCom:add")
//    String adds(){
//
//        return "jzweb/examinationBatchCom/adds";
//    }


    @GetMapping("/edits")
    @RequiresPermissions("jzweb:examinationBatchCom:edit")
    String edits(Long id,Model model,Long cbatchId){
        ExaminationBatchComSDO examinationBatchCom = examinationBatchComServices.selectById(id);

        //拼接模版信息
        if(Objects.nonNull(examinationBatchCom.getModileId())){

            JzJinzhuanDispositionModule jinzhuanDispositionModule = new JzJinzhuanDispositionModule().setId(examinationBatchCom.getModileId());
            List<JzJinzhuanDispositionModule> modules = dispositionModuleService.getModuleList(jinzhuanDispositionModule);
            if(!modules.isEmpty()){
                jinzhuanDispositionModule = modules.get(0);
            }
            examinationBatchCom.setDispositionModule(jinzhuanDispositionModule);
        }
        model.addAttribute("cbatchId", cbatchId);
        model.addAttribute("examinationBatchCom", examinationBatchCom);
        return "jzweb/examinationBatchCom/edits";
    }



    @GetMapping("/edit/{id}")
    @RequiresPermissions("jzweb:examinationBatchCom:edit")
    String edit(@PathVariable("id") Long id,Model model){
        ExaminationBatchComDO examinationBatchCom = examinationBatchComService.selectById(id);
        model.addAttribute("examinationBatchCom", examinationBatchCom);
        return "jzweb/examinationBatchCom/edit";
    }

    @Log("添加考试批次")
    @ResponseBody
    @PostMapping("/save")
    @RequiresPermissions("jzweb:examinationBatchCom:add")
    public Result<String> save( ExaminationBatchComDO examinationBatchCom){
        examinationBatchCom.setCreateId(this.getUserId());
//        List<JzJinzhuanDispositionTopic> dispositionTopic = examinationBatchCom.getDispositionModule().getDispositionTopic();//模板任务集合
        //拿出任务配置的所有裁判id组成id的字符串
//        String refereeId = "";
//        for (int i = 0 ;i < dispositionTopic.size();i++){
//                if (!dispositionTopic.get(i).getRefereeId().equals("") && dispositionTopic.get(i).getRefereeId() != null){
//                    refereeId = dispositionTopic.get(i).getRefereeId() + ";;" + refereeId;
//                }
//        }
//        examinationBatchCom.setRefereeId(refereeId);
        examinationBatchComService.insert(examinationBatchCom);
        return Result.ok();
    }

    @Log("查询对应赛道匹配的裁判")
    @ResponseBody
    @RequestMapping(value = "/getUserReferee", method = RequestMethod.POST)
    public Object getUserReferee(@RequestBody Map<String,Object> map){
        //根据传入的参数判断是否是B-C赛场或者A赛场（0-1,0：B-C赛场裁判，1：A赛场裁判）
          //加一个对应赛区的裁判（竞赛一级管理员或工作人员在模板配置对应裁判时，查询出对应赛区的裁判数据）
        if (!StringUtils.isBlank(this.getUser().getTrack()) && this.getUser().getTrack().equals("E")){
                //如果裁判标识不为空且值为E说明是是竞赛一级管理员
                    //条件为登录人对应的赛区
            map.put("competitionAreaId",this.getUser().getCompetitionAreaId());
        }else if (!StringUtils.isBlank(this.getUser().getTrack()) && this.getUser().getTrack().equals("D")){
                //工作人员
            map.put("competitionAreaId",this.getUser().getCompetitionAreaId());
        }
        List<Map> list=  userRelevancyService.listUserRele(map);
        return Result.ok(list);
    }


    @Log("修改考试批次")
    @ResponseBody
    @RequestMapping("/updates")
    @RequiresPermissions("jzweb:examinationBatchCom:edit")
    public Result<String>  updates( ExaminationBatchComSDO examinationBatchCom){
        long m = ((examinationBatchCom.getEndTime().getTime()-examinationBatchCom.getStartTime().getTime())/1000/60);
            if(m<=0){
                return Result.fail("结束时间不能小于或等于开始时间！");
            }
        ExaminationBatchComSDO examinationBatchComSDO= examinationBatchComServices.findOneByKv("name",examinationBatchCom.getName().replaceAll(" ",""),"pid",examinationBatchCom.getIds(),"cbatch_id",examinationBatchCom.getCbatchId());
        if(examinationBatchComSDO!=null){
            if(!examinationBatchComSDO.getId().toString().equals(examinationBatchCom.getId().toString())){
                return Result.fail("赛场已存在！");
            }

        }
        JzJinzhuanDispositionTopic jzJinzhuanDispositionTopic = new JzJinzhuanDispositionTopic();
        jzJinzhuanDispositionTopic.setId(examinationBatchCom.getModileId());
        //查询出配置的模板数据
        Wrapper wrapper = new EntityWrapper();
        wrapper.eq("module_id",examinationBatchCom.getModileId());
        List<JzJinzhuanDispositionTopic> jzJinzhuanDispositionTopics = dispositionTopicService.selectList(wrapper);
        ArrayList<String>	ids	=	new ArrayList<>();
        //将对应任务下的裁判都配置到赛场上去
        for (int i = 0;i < jzJinzhuanDispositionTopics.size();i++){
                //循环出任务已经配置了的裁判
            ids.add(jzJinzhuanDispositionTopics.get(i).getRefereeId());
        }
        //裁判的字符串
        String refeereid = "";
        for (int i = 0;i < ids.size();i++){
            refeereid =  ids.get(i) + "," + refeereid;
        }
        refeereid.replace("","");
        //模板配置的裁判id
        //将模板任务表的裁判id存入赛场表
        ExaminationBatchComDO examinationBatchComDO = new ExaminationBatchComDO();
        examinationBatchComDO.setId(examinationBatchCom.getIds());//赛场id
        examinationBatchComDO.setRefereeId(refeereid);//裁判id
        examinationBatchComService.updateById(examinationBatchComDO);

        boolean update = examinationBatchComServices.updateById(examinationBatchCom);
        return update ? Result.ok() : Result.fail();
    }


    @Log("修改考试批次")
    @ResponseBody
    @RequestMapping("/update")
    @RequiresPermissions("jzweb:examinationBatchCom:edit")
    public Result<String>  update( ExaminationBatchComDO examinationBatchCom){
        boolean update = examinationBatchComService.updateById(examinationBatchCom);
        return update ? Result.ok() : Result.fail();
    }

    @Log("删除考试批次")
    @PostMapping( "/remove")
    @ResponseBody
    @RequiresPermissions("jzweb:examinationBatchCom:remove")
    public Result<String>  remove( Long id){
        examinationBatchComService.deleteById(id);
        return Result.ok();
    }

    @Log("批量删除考试批次")
    @PostMapping( "/batchRemove")
    @ResponseBody
    @RequiresPermissions("jzweb:examinationBatchCom:batchRemove")
    public Result<String>  remove(@RequestParam("ids[]") Long[] ids){
        examinationBatchComService.deleteBatchIds(Arrays.asList(ids));
        return Result.ok();
    }

    @Log("根据所述竞赛id查询子竞赛")
    @PostMapping( "/getBathComsByPid")
    @ResponseBody
    @ApiOperation(value = "竞赛平台-竞赛考试批次管理", notes = "根据所述竞赛id查询子竞赛")
    public Result<List<ExaminationBatchComSDO>>  getBathComsByPid(@RequestParam("pid") Long pid){
        List<Map<String,Object>> mo = new ArrayList<>();
        List<Map<String,Object>> cj = new ArrayList<>();

        mo.forEach(i ->{

        });


        List<ExaminationBatchComDO> examinationBatchComDOs = examinationBatchComService.selectList(new EntityWrapper<ExaminationBatchComDO>().eq("cbatch_id",pid));
        List<Long> ids = examinationBatchComDOs.stream().map(ExaminationBatchComDO::getId).distinct().collect(Collectors.toList());
        List<ExaminationBatchComSDO> examinationBatchComSDOS = examinationBatchComServices.selectList(new EntityWrapper<ExaminationBatchComSDO>().in("pid",ids));
        return Result.ok(examinationBatchComSDOS);
    }
}
